//
//  HomeViewController.m
//  Pictorial
//
//  Created by SKY on 15/12/28.
//  Copyright © 2015年 sky. All rights reserved.
//

#import "HomeViewController.h"
#import "SettingViewController.h"
#import "PictorialViewController.h"
#import "WallpaperViewController.h"
#import "DownloadViewController.h"

#import "HomeView.h"
#import "HomeDatePage.h"
#import "HomeCommonPage.h"

#import "HomeDateModel.h"
#import "HomeCommonModel.h"

#import "Net.h"
#import "UMSocial.h"

#define BACKSIZE        35
#define BACKPOSITION    40

@interface HomeViewController ()<UIScrollViewDelegate,HomeMoreDelegate,SettingViewControllerDelegate,HomeCommonPageDelegate>
{
    CGFloat _contentWidth;
    CGFloat _contentHeight;
    
    int _number;
}
@property (nonatomic,weak) HomeView *homeView;

@property (nonatomic,assign) int page;
@property (nonatomic,strong) NSMutableArray *pageArray;
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UIButton *backBtn;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createUI];
    
    [self downloadData:0];
    
}
-(void)downloadData:(int)page{
    
    self.page = page;
    
    [self.pageArray addObject:[NSString stringWithFormat:@"%d",page]];
    
    NSInteger nowDate = [[[NSDate today] year] integerValue];
    NSInteger lastDate = [[[NSDate dateFromDay:page] year] integerValue];
    
    //只提供最多一年的数据
    if(((nowDate - lastDate) > 1)||[[[NSDate dateFromDay:page] year] isEqualToString:@"2014"]){
        
        UILabel *alertLabel = [UILabel labelWithText:@"~无更多内容~" fontSize:14 frame:CGRectMake(0, 0, 200, 40) color:[UIColor whiteColor] textAlignment:1];
        [self.view addSubview:alertLabel];
        alertLabel.backgroundColor = [UIColor blackColor];
        alertLabel.alpha = 0;
        [UIView animateWithDuration:1.0 animations:^{
            alertLabel.alpha = 1;
        } completion:^(BOOL finished) {
            alertLabel.alpha = 0;
            return;
        }];
    }
    
    NSString *dateURL = [NSString stringWithFormat:HOME_URL,[NSDate dateFromDay:page]];
    
    NSMutableArray *array = [NSMutableArray array];
    [Net getRequestHttpURL:dateURL view:self.view completation:^(id object) {
        
        NSDictionary *dict = object;
        
        HomeDateModel *dateModel = [HomeDateModel objectWithDict:dict];
        [array addObject:dateModel];
        
        NSArray *articles = dict[@"articles"];
        for (NSDictionary *subDict in articles) {
            HomeCommonModel *model = [HomeCommonModel objectWithDict:subDict];
            [array addObject:model];
        }
        [self.dataArray addObject:array];
        [self loadViewAtPage:page];
    }];
}
-(void)loadViewAtPage:(int)page{
    
    NSArray *array = self.dataArray[page];
    
    CGFloat x = _contentWidth;
    CGFloat y = 0;
    CGFloat w = WIDTH;
    CGFloat h = HEIGHT;
    for (int i = 0; i < array.count; i ++) {
        if (i == 0) {
            HomeDatePage *datePage = [HomeDatePage nibInitializtion];
            datePage.frame = CGRectMake(x, y, w, h);
            [self.homeView addSubview:datePage];
            datePage.delegate = self;
            
            HomeDateModel *model = array[i];
            datePage.model = model;
            
            datePage.page = self.page;
            
        }else{
            HomeCommonPage *commonPage = [HomeCommonPage nibInitializtion];
            commonPage.frame = CGRectMake(x + i * w, y, w, h);
            [self.homeView addSubview:commonPage];
            
            [commonPage addNavBar];
            
            commonPage.moreDelegate = self;
            commonPage.shareDelegate = self;
            
            HomeCommonModel *model = array[i];
            commonPage.model = model;
        }
    }
    _contentHeight = h;
    _contentWidth += w * array.count;
    
    self.homeView.contentSize = CGSizeMake(_contentWidth, _contentHeight);
}

#pragma mark - HomeMoreDelegate
-(void)moveToVC:(NSInteger)index{
    switch (index) {
        case 0:{
            PictorialViewController *pictorialVC = [PictorialViewController classInitializtion];
            [self presentViewController:pictorialVC animated:YES completion:nil];
            break;
        }
        case 1:{
            WallpaperViewController *wallpaperVC = [WallpaperViewController classInitializtion];
            [self presentViewController:wallpaperVC animated:YES completion:nil];
            break;
        }
        case 2:{
            DownloadViewController *downloadVC = [DownloadViewController classInitializtion];
            [self presentViewController:downloadVC animated:YES completion:nil];
            break;
        }
    }
}
#pragma mark - HomeCommonPageDelegate
-(void)shareWithContent:(NSString *)content picture:(NSString *)picture platform:(NSInteger)type{
    
    NSArray *array = @[UMShareToSina,UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite];
    
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picture]]];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[array[type]] content:content image:image location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *shareResponse){
        if (shareResponse.responseCode == UMSResponseCodeSuccess) {
            DEBUGLog(@"分享成功！");
        }
    }];
}
#pragma mark - HomeMoreDelegate
-(void)more{
    SettingViewController *settingVC = [SettingViewController classInitializtion];
    settingVC.delegate = self;
    [self addChildViewController:settingVC];
    [self.view addSubview:settingVC.view];
}
#pragma mark - ScrollViewDelagete
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int index = scrollView.contentOffset.x / scrollView.frame.size.width + 1;
    int page = scrollView.contentSize.width / scrollView.frame.size.width;
    
    if (index >= 5) {
        self.backBtn.alpha = 1;
    }else{
        self.backBtn.alpha = 0;
    }
    if(index != page){
        return;
    }
    _number ++;

    for (NSString *str in self.pageArray) {
        
        if ([str isEqualToString:[NSString stringWithFormat:@"%d",_number]]) {
            return;
        }
    }
    
    [self downloadData:_number];
    
}
-(void)createUI{
    
    HomeView *homeView = [HomeView classInitializtion];
    [self.view addSubview:homeView];
    self.homeView = homeView;
    homeView.frame = self.view.bounds;
    homeView.delegate = self;

}
-(void)backToStart{
    [self.homeView setContentOffset:CGPointZero animated:YES];
    self.backBtn.alpha = 0;
}
-(UIButton *)backBtn{
    if (_backBtn == nil) {
        _backBtn = [UIButton buttonWithLocalBgImage:@"backToStart.png" frame:CGRectMake(WIDTH - BACKPOSITION, HEIGHT - BACKPOSITION, BACKSIZE, BACKSIZE) target:self sel:@selector(backToStart)];
        [self.view addSubview:_backBtn];
        [self.view bringSubviewToFront:_backBtn];
    }
    return _backBtn;
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
-(NSMutableArray *)pageArray{
    if (_pageArray == nil) {
        _pageArray = [NSMutableArray array];
    }
    return _pageArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
